package net.wwang.blog.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.wwang.blog.commons.global.Constants;
import net.wwang.blog.commons.global.GlobalTipMsg;
import net.wwang.blog.commons.global.ResponseResult;
import net.wwang.blog.dao.CommentDao;
import net.wwang.blog.pojo.Comment;
import net.wwang.blog.pojo.User;
import net.wwang.blog.service.CommentService;
import net.wwang.blog.service.UserService;
import net.wwang.blog.util.CookieUtil;
import net.wwang.blog.util.IDGenerateUtil;
import net.wwang.blog.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author WangWei
 * @date 2020/8/14
 */
@Service
@Slf4j
@Transactional
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentDao commentDao;
    @Autowired
    private UserService userService;
    @Autowired
    private IDGenerateUtil IDGenerateUtil;
    @Override
    public ResponseResult addComment(Comment comment, HttpServletRequest request, HttpServletResponse response) {
        String tokenKey = CookieUtil.getCookie(request, Constants.User.SYSTEM_COOKIE_TOKEN);
        if(Utils.isEmpty(tokenKey)) {
            return ResponseResult.UN_AUTHORIZED(GlobalTipMsg.ACCOUNT_NOT_LOGIN);
        }
        User user = userService.checkUserState(request, response);
        if (user == null) {
            return ResponseResult.UN_AUTHORIZED(GlobalTipMsg.ACCOUNT_NOT_LOGIN);
        }
        comment.setUid(user.getId());
        comment.setUserAvatar(user.getAvatar());
        comment.setUserName(user.getUsername());
        //默认正常，0表示评论删除
        comment.setState("1");
        comment.setId(String.valueOf(IDGenerateUtil.nextId()));
        commentDao.save(comment);
        log.info("用户："+comment.getUserName()+"评论了----"+comment.getContent());
        return ResponseResult.SUCCESS(GlobalTipMsg.COMMENT_SUCESS).setData(comment);
    }
}
